//
// Created by antler on 2018/12/19.
//

#include "UIContext.h"

#include "GlobalMacros.h"

#include <string>

#include "log.h"

#include "UIContextUtils.h"

UIContext::UIContext()
        : mUIContextObj(nullptr) {

}

UIContext::~UIContext() {
    close();
    releaseUIContextObject();
}

bool UIContext::initWith(jobject juicontext, const std::string &layout, const std::string &style) {
    LOGV("UIContext::initWith uicontext:%p\nlayout:%s\nstyle:%s", juicontext, layout.c_str(),
         style.c_str());
    setUIContextObject(juicontext);
    return true;
}

void UIContext::show() {
    if (isOk()) {
        UIContextUtils::show(mUIContextObj);
    }
}

void UIContext::close() {
    if (isOk()) {
        UIContextUtils::close(mUIContextObj);
    }
}

UIView *UIContext::getRootView() {
    UIView *uiview = nullptr;

    do {
        if (!isOk()) {
            break;
        }

        jobject juiview = UIContextUtils::getRootView(mUIContextObj);
        if (!juiview) {
            break;
        }

        uiview = new(std::nothrow)UIView();
        if (!uiview) {
            break;
        }

        uiview->initWith(juiview);
    } while (0);

    return uiview;
}

UIView *UIContext::findView(const std::string &id) {
    UIView *uiview = nullptr;

    do {
        if (!isOk()) {
            break;
        }

        jobject juiview = UIContextUtils::findView(mUIContextObj, id);
        if (!juiview) {
            break;
        }

        uiview = new(std::nothrow)UIView();
        if (!uiview) {
            break;
        }

        uiview->initWith(juiview);
    } while (0);

    return uiview;
}

UIView *UIContext::createView(const std::string &layout) {
    jobject juiview = UIContextUtils::createView(mUIContextObj, layout);
    if (juiview) {
        UIView *uiview = new(std::nothrow) UIView();
        if (uiview) {
            uiview->initWith(juiview);
            return uiview;
        }
    }
    return nullptr;
}

bool UIContext::isOk() {
    return mUIContextObj != nullptr;
}

jobject UIContext::getUIContextObject() {
    return mUIContextObj;
}

void UIContext::setUIContextObject(jobject juicontext) {
    releaseUIContextObject();

    JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
    if (!env) {
        return;
    }

    if (juicontext) {
        mUIContextObj = env->NewGlobalRef(juicontext);
    }
}

void UIContext::releaseUIContextObject() {
    JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
    if (!env) {
        return;
    }

    if (isOk()) {
        env->DeleteGlobalRef(mUIContextObj);
        mUIContextObj = nullptr;
    }
}

